import React, { useMemo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "@/App.css";
import { Route, Routes } from "react-router-dom";
import MainLayout from "@/mainLayout";
import Login from "@/pages/login";
import { useAppDispatch, useAppSelector } from "@/app/hooks";
import { UserRouteState, verifySuccess } from "@/app/user/userSlice";
import { routerObject } from "@/router/routes";
import axios from "axios";

function generateRoutes(routes: UserRouteState[]) {
  const flatRoutes = routes.reduce(
    (p, n) => (n.children ? p.concat(n.children) : p.concat(n)),
    [] as UserRouteState[]
  );
  

  return flatRoutes.map((v, i) => {
    if (v.ps_api_path === "/") {
      return (
        <Route key={i} index element={routerObject[v.ps_api_service]}></Route>
      );
    }
    return (
      <Route
        key={i}
        path={v.ps_api_path}
        element={routerObject[v.ps_api_service]}
      ></Route>
    );
  });
}

function App() {
  const routes = useAppSelector((state) => state.user.routes);
  const token = useAppSelector((state) => state.user.token);
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  // const dynamicRoutes = useMemo(() => {
  //   return generateRoutes(routes);
  // }, [routes]);
  const dynamicRoutes = generateRoutes(routes);
  
  useEffect(() => {
    if (token) {
      (async () => {
        try {
          const result = await axios.get("/api/user/info");
          dispatch(verifySuccess(result));
        } catch {
          console.log("用户权限获取失败");
        }
      })();
    } else {
      navigate("/login");
    }
  }, [token]);

  return (
    <div>
      <Routes>
        <Route path="/" element={<MainLayout></MainLayout>}>
          {dynamicRoutes}
          <Route path="*" element={<div>404</div>}></Route>
        </Route>
        <Route path="/login" element={<Login></Login>}></Route>
      </Routes>
    </div>
  );
}

export default App;
